package com.bilu.common.utility;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;

public class ResponseUtility {
	public static void response(HttpServletResponse response, String templateId, String fileName, Map<String, Object> data, Configure configure) {
    	Resource resource = new ClassPathResource("template/" + templateId + ".docx");
    	response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=".concat(URLEncoderUtility.encode(fileName)));
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        try {
        	outputStream = response.getOutputStream();
        	bufferedInputStream = new BufferedInputStream(new FileInputStream(resource.getFile()));
        	
        	if(configure == null) {
        		XWPFTemplate.compile(resource.getFile()).render(data).writeAndClose(outputStream);
        	}else {
        		XWPFTemplate.compile(resource.getFile(), configure).render(data).writeAndClose(outputStream);
        	}
        	outputStream.write(bufferedInputStream.readAllBytes());
        	response.flushBuffer();
        }catch(Exception e) {
        	e.printStackTrace();
        }finally {
        	StreamUtility.closeStream(bufferedInputStream);
        	StreamUtility.closeStream(outputStream);
        }
	}
	
	public static void response(HttpServletResponse response, String message){
		if(message != null){
			response.setCharacterEncoding(StandardCharsets.UTF_8.name());
			response.setHeader("Cache-Control", "no-cache");
			response.setContentType("text/plain");
			try {
				response.setContentLength(message.getBytes(StandardCharsets.UTF_8).length);
				response.getWriter().append(message);
				response.getWriter().flush();
				response.getWriter().close();
			}catch (Exception ignored) {
				
			}
		}
	}
}
